package com.longcai.cm.utils;

import cn.hutool.core.codec.Base64;
import com.longcai.cm.exception.SysRuntimeException;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author libingxing
 */
public class QrCodeUtil {

    public static void main(String[] args) throws IOException, WriterException {
        System.err.println(generateQRCodeImage("123456", 100, 100));
    }

    public static String generateQRCodeImage(String text, int width, int height) throws WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();

        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);

        final BufferedImage qrImage = MatrixToImageWriter.toBufferedImage(bitMatrix);

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        try {
            ImageIO.write(qrImage, "png", stream);
        } catch (IOException e) {
            throw new SysRuntimeException("二维码生成失败");
        }
        stream.flush();
        stream.close();
        return "data:image/png;base64," + Base64.encode(stream.toByteArray());

    }


}
